Face Generation

In this project, you'll use generative adversarial networks to generate new images of faces.

Get the Data

You'll be using two datasets in this project:

  • MNIST
  • CelebA

Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner.

If you're using FloydHub, set data_dir to "/input" and use the FloydHub data ID "R5KrjnANiKVhLWAkpXhNBe".

In [14]:
#data_dir = './data'

# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
data_dir = '/input'


"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper

helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
Found mnist Data
Found celeba Data

Explore the Data

MNIST

As you're aware, the MNIST dataset contains images of handwritten digits. You can view the first number of examples by changing show_n_images.

In [15]:
show_n_images = 25

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
import os
from glob import glob
from matplotlib import pyplot

mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')
Out[15]:
<matplotlib.image.AxesImage at 0x7fceafa7d278>

CelebA

The CelebFaces Attributes Dataset (CelebA) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing show_n_images.

In [16]:
show_n_images = 25

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))
Out[16]:
<matplotlib.image.AxesImage at 0x7fceaf9ed400>

Preprocess the Data

Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.

The MNIST images are black and white images with a single color channel while the CelebA images have 3 color channels (RGB color channel).

Build the Neural Network

You'll build the components necessary to build a GANs by implementing the following functions below:

  • model_inputs
  • discriminator
  • generator
  • model_loss
  • model_opt
  • train

Check the Version of TensorFlow and Access to GPU

This will check to make sure you have the correct version of TensorFlow and access to a GPU

In [17]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf

# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer.  You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))

# Check for a GPU
if not tf.test.gpu_device_name():
    warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
TensorFlow Version: 1.1.0
Default GPU Device: /gpu:0

Input

Implement the model_inputs function to create TF Placeholders for the Neural Network. It should create the following placeholders:

  • Real input images placeholder with rank 4 using image_width, image_height, and image_channels.
  • Z input placeholder with rank 2 using z_dim.
  • Learning rate placeholder with rank 0.

Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)

In [18]:
import problem_unittests as tests

def model_inputs(image_width, image_height, image_channels, z_dim):
    """
    Create the model inputs
    :param image_width: The input image width
    :param image_height: The input image height
    :param image_channels: The number of image channels
    :param z_dim: The dimension of Z
    :return: Tuple of (tensor of real input images, tensor of z data, learning rate)
    """
    # TODO: Implement Function
    input_real = tf.placeholder(tf.float32, [None, image_width, image_height, image_channels], name="input_real")
    input_z = tf.placeholder(tf.float32, [None, z_dim], name="input_z")
    learning_rate = tf.placeholder(tf.float32, name="learning_rate")
    return input_real, input_z, learning_rate


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
Tests Passed

Discriminator

Implement discriminator to create a discriminator neural network that discriminates on images. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).

In [19]:
drop_rate = 0.2
alpha = 0.15
smooth = 0.2
In [20]:
def LeakyReLU(inputs):
    return tf.maximum(inputs * alpha, inputs)

def xavier_init(size, dtype, partition_info):
    
    in_dim = size[-1]
    xavier_stddev = 1. / tf.sqrt(in_dim * 1.)
    return tf.random_normal(shape=size, stddev=xavier_stddev, dtype=dtype)

def kinit(size, dtype, partition_info):
    return tf.random_normal(shape=size, stddev=0.02, dtype=dtype)

def discriminator(images, reuse=False, is_training=True):
    """
    Create the discriminator network
    :param images: Tensor of input image(s)
    :param reuse: Boolean if the weights should be reused
    :return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
    """
    # TODO: Implement Function
    with tf.variable_scope("discriminator", reuse=reuse):

        x1 = tf.layers.conv2d(images, 64, 3, padding="same", activation=None, kernel_initializer=kinit)

        relu1 = LeakyReLU(x1)

        
        x2 = tf.layers.conv2d(relu1, 128, 3, padding="same", activation=None, kernel_initializer=kinit)


        bn2 = tf.layers.batch_normalization(x2, training=is_training)
        relu2 = LeakyReLU(bn2)

        
        x3 = tf.layers.conv2d(relu2, 512, 3, padding="same", activation=None, kernel_initializer=kinit)

        
        bn3 = tf.layers.batch_normalization(x3, training=is_training)
        relu3 = LeakyReLU(bn3)

        
        flat = tf.contrib.layers.flatten(relu3)
        output = tf.layers.dense(flat, 1)
    
    return tf.nn.sigmoid(output), output


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)
Tests Passed

Generator

Implement generator to generate an image using z. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x out_channel_dim images.

In [21]:
def generator(z, out_channel_dim, is_train=True):
    """
    Create the generator network
    :param z: Input z
    :param out_channel_dim: The number of channels in the output image
    :param is_train: Boolean if generator is being used for training
    :return: The tensor output of the generator
    """
    # TODO: Implement Function
    with tf.variable_scope("generator", reuse=not is_train):
        x1 = tf.layers.dense(z, 7*7*512)
        x1 = tf.reshape(x1, (-1, 7, 7, 512))
        x1 = tf.layers.batch_normalization(x1, training=is_train)
        x1 = LeakyReLU(x1)
        
        x2 = tf.layers.conv2d_transpose(x1, 512, 3, strides=2, padding="same", kernel_initializer=kinit)
        x2 = tf.layers.batch_normalization(x2, training=is_train)
        x2 = LeakyReLU(x2)
        
        x3 = tf.layers.conv2d_transpose(x2, 64, 3, strides=2, padding="same", kernel_initializer=kinit)
        x3 = tf.layers.batch_normalization(x3, training=is_train)
        x3 = LeakyReLU(x3)
        
        x4 = tf.layers.conv2d_transpose(x3, 64, 3, strides=1, padding="same", kernel_initializer=kinit)
        x4 = tf.layers.batch_normalization(x4, training=is_train)
        x4 = LeakyReLU(x4)
        
        logits = tf.layers.conv2d_transpose(x4, out_channel_dim, 5, strides=1, padding="same", kernel_initializer=kinit)
        
        g = tf.tanh(logits)

    return g


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_generator(generator, tf)
Tests Passed

Loss

Implement model_loss to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:

  • discriminator(images, reuse=False)
  • generator(z, out_channel_dim, is_train=True)
In [22]:
def model_loss(input_real, input_z, out_channel_dim, batch_size=32):
    """
    Get the loss for the discriminator and generator
    :param input_real: Images from the real dataset
    :param input_z: Z input
    :param out_channel_dim: The number of channels in the output image
    :return: A tuple of (discriminator loss, generator loss)
    """
    # TODO: Implement Function
    D_real_out, D_real_digits = discriminator(input_real, reuse=False)
    G_model = generator(input_z, out_channel_dim, True)
    D_fake_out, D_fake_digits = discriminator(G_model, reuse=True)

    
    d_loss_real = tf.reduce_mean(
        tf.nn.sigmoid_cross_entropy_with_logits(logits=D_real_digits, 
                                                labels=tf.ones_like(D_real_out) * (1.0 - smooth))
    )
    d_loss_fake = tf.reduce_mean(
        tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake_digits,
                                               labels=tf.ones_like(D_fake_out) * (smooth))
    )
    G_loss = tf.reduce_mean(
        tf.nn.sigmoid_cross_entropy_with_logits(logits=D_fake_digits,
                                               labels=tf.ones_like(D_fake_out))
    )
    D_loss = d_loss_real + d_loss_fake
    
    
    #G_loss = -tf.reduce_mean(D_fake_digits)
    #D_loss = tf.reduce_mean(D_fake_digits) - tf.reduce_mean(D_real_digits)
    
    return D_loss, G_loss


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)
Tests Passed

Optimization

Implement model_opt to create the optimization operations for the GANs. Use tf.trainable_variables to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation).

In [23]:
def model_opt(d_loss, g_loss, learning_rate, beta1):
    """
    Get optimization operations
    :param d_loss: Discriminator loss Tensor
    :param g_loss: Generator loss Tensor
    :param learning_rate: Learning Rate Placeholder
    :param beta1: The exponential decay rate for the 1st moment in the optimizer
    :return: A tuple of (discriminator training operation, generator training operation)
    """
    # TODO: Implement Function
    variables = tf.trainable_variables()
    d_var = [var for var in variables if var.name.startswith('discriminator')]
    g_var = [var for var in variables if var.name.startswith("generator")]
    with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
        D_solver = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(d_loss,
                                                                                            var_list=d_var)
        G_solver = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(g_loss,
                                                                                            var_list=g_var)

    return D_solver, G_solver


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)
Tests Passed

Neural Network Training

Show Output

Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training.

In [24]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np

def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
    """
    Show example output for the generator
    :param sess: TensorFlow session
    :param n_images: Number of Images to display
    :param input_z: Input Z Tensor
    :param out_channel_dim: The number of channels in the output image
    :param image_mode: The mode to use for images ("RGB" or "L")
    """
    cmap = None if image_mode == 'RGB' else 'gray'
    z_dim = input_z.get_shape().as_list()[-1]
    example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])

    samples = sess.run(
        generator(input_z, out_channel_dim, False),
        feed_dict={input_z: example_z})

    images_grid = helper.images_square_grid(samples, image_mode)
    pyplot.imshow(images_grid, cmap=cmap)
    pyplot.show()

Train

Implement train to build and train the GANs. Use the following functions you implemented:

  • model_inputs(image_width, image_height, image_channels, z_dim)
  • model_loss(input_real, input_z, out_channel_dim)
  • model_opt(d_loss, g_loss, learning_rate, beta1)

Use the show_generator_output to show generator output while you train. Running show_generator_output for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the generator output every 100 batches.

In [25]:
losses = []
import time
def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode, 
          save_folder=None, base_i=0, load_path=None):
    """
    Train the GAN
    :param epoch_count: Number of epochs
    :param batch_size: Batch Size
    :param z_dim: Z dimension
    :param learning_rate: Learning Rate
    :param beta1: The exponential decay rate for the 1st moment in the optimizer
    :param get_batches: Function to get batches
    :param data_shape: Shape of the data
    :param data_image_mode: The image mode to use for images ("RGB" or "L")
    """
    # TODO: Build Model
    input_real, input_z, lr = model_inputs(data_shape[1], data_shape[2], data_shape[3], z_dim)
    d_loss, g_loss = model_loss(input_real, input_z, data_shape[3], batch_size)
    d_solver, g_solver = model_opt(d_loss, g_loss, lr, beta1)

    tf.contrib.layers.summarize_tensors(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES))
    tf.summary.scalar("d_loss", d_loss)
    tf.summary.scalar("g_loss", g_loss)
    
    merge_all = tf.summary.merge_all()
    if save_folder and not os.path.exists(save_folder):
        os.mkdir(save_folder)
        
    tf.contrib.layers.summaries.summarize_variables()
    global alpha, drop_rate, smooth

    with tf.Session() as sess:
        print("begin train")
        saver = tf.train.Saver()
        if load_path:
            saver.restore(sess, load_path)
        else:
            sess.run(tf.global_variables_initializer())
        
        graph = tf.get_default_graph()
        writer = tf.summary.FileWriter("log/{}/lr={} bet={} smooth={} al={} dr={} zdim={}/6".format(save_path, learning_rate,
                                                                                      beta1,
                                                                                      smooth,
                                                                                      alpha,
                                                                                      drop_rate, 
                                                                                      z_dim), graph)
        begin_time = time.time()
        count = 0
        for epoch_i in range(epoch_count):
            for batch_images in get_batches(batch_size):
                # TODO: Train Model
                batch_images *= 2.0
                
                batch_z = np.random.normal(0., 1., size=(batch_size, z_dim))
                for d_i in range(1):
                    # train discriminator more
                    _ = sess.run(d_solver, feed_dict={input_real: batch_images, 
                                                  input_z: batch_z, 
                                                  lr: learning_rate})
                for d_i in range(2):
                    _ = sess.run(g_solver, feed_dict={
                        input_real: batch_images, 
                        input_z: batch_z,
                        lr: learning_rate
                    })
                train_loss_d, train_loss_g, summary = sess.run([d_loss, g_loss, merge_all], feed_dict={
                    input_z: batch_z, input_real:batch_images
                })
                count += 1
                writer.add_summary(summary, count)
                losses.append((train_loss_d, train_loss_g))
                if count % 250 == 0:
                    interval = (time.time() - begin_time) / 50.
                    begin_time = time.time()
                    print("Epoch {}".format(count),
                          "Each train cost time: {}".format(interval),
                         "Discriminator Loss: {:.4f} ".format(train_loss_d),
                         "Generator Loss: {:.4f}".format(train_loss_g))
                    show_generator_output(sess, 25, input_z, data_shape[3], data_image_mode)
                    showLoss()
                
                if save_folder and count % 800 == 0:

                    saver.save(sess, "{}/lr={} bet={} smooth={} al={} dr={}.ckpt".format(save_folder,
                                                                  learning_rate,
                                                                  beta1,
                                                                  smooth,
                                                                  alpha,
                                                                  drop_rate))
        showLoss()
def showLoss():
    fig, ax = pyplot.subplots()
    loss_ar = np.array(losses)
    pyplot.plot(loss_ar.T[0], label="discriminator", alpha=0.5)
    pyplot.plot(loss_ar.T[1], label="generator", alpha=0.5)
    pyplot.title("Training loss")
    pyplot.legend()
    pyplot.show()

MNIST

Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.

In [13]:
batch_size = 32
z_dim = 100
learning_rate = 2e-4
beta1 = 0.45

losses = []
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 2
save_path = "mnist_save"

mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
with tf.Graph().as_default():
    train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
          mnist_dataset.shape, mnist_dataset.image_mode, save_path)
begin train
Epoch 50 Each train cost time: 0.9043863391876221 Discriminator Loss: 3.7083  Generator Loss: 3.5371
Epoch 100 Each train cost time: 0.9146549320220947 Discriminator Loss: 1.8062  Generator Loss: 1.6721
Epoch 150 Each train cost time: 0.8977641201019287 Discriminator Loss: 3.0959  Generator Loss: 0.1109
Epoch 200 Each train cost time: 0.8868900489807129 Discriminator Loss: 5.3178  Generator Loss: 4.4981
Epoch 250 Each train cost time: 0.8930080461502076 Discriminator Loss: 3.4768  Generator Loss: 0.0599
Epoch 300 Each train cost time: 0.8876950979232788 Discriminator Loss: 4.0169  Generator Loss: 0.0630
Epoch 350 Each train cost time: 0.9206836986541748 Discriminator Loss: 4.4580  Generator Loss: 0.0365
Epoch 400 Each train cost time: 0.9035069131851197 Discriminator Loss: 4.2038  Generator Loss: 0.0440
Epoch 450 Each train cost time: 0.899337830543518 Discriminator Loss: 1.6422  Generator Loss: 1.5554
Epoch 500 Each train cost time: 0.8997461414337158 Discriminator Loss: 3.6753  Generator Loss: 0.0714
Epoch 550 Each train cost time: 0.9129554414749146 Discriminator Loss: 2.7033  Generator Loss: 0.0964
Epoch 600 Each train cost time: 0.9096749687194824 Discriminator Loss: 3.1786  Generator Loss: 0.0918
Epoch 650 Each train cost time: 0.9317507171630859 Discriminator Loss: 2.0693  Generator Loss: 0.2022
Epoch 700 Each train cost time: 0.8993927431106568 Discriminator Loss: 2.3285  Generator Loss: 1.2792
Epoch 750 Each train cost time: 0.8962973499298096 Discriminator Loss: 2.3429  Generator Loss: 0.2102
Epoch 800 Each train cost time: 0.8908507347106933 Discriminator Loss: 1.6871  Generator Loss: 0.6058
Epoch 850 Each train cost time: 0.8893480968475341 Discriminator Loss: 1.7280  Generator Loss: 0.8141
Epoch 900 Each train cost time: 0.9018356990814209 Discriminator Loss: 1.5546  Generator Loss: 1.4308
Epoch 950 Each train cost time: 0.9121813678741455 Discriminator Loss: 2.3964  Generator Loss: 0.1770
Epoch 1000 Each train cost time: 0.8876502227783203 Discriminator Loss: 1.5742  Generator Loss: 0.5286
Epoch 1050 Each train cost time: 1.1398585939407349 Discriminator Loss: 4.0423  Generator Loss: 0.0819
Epoch 1100 Each train cost time: 0.903440375328064 Discriminator Loss: 2.0664  Generator Loss: 1.7919
Epoch 1150 Each train cost time: 0.8984064102172852 Discriminator Loss: 2.0852  Generator Loss: 0.2231
Epoch 1200 Each train cost time: 0.8994904041290284 Discriminator Loss: 1.9057  Generator Loss: 0.2691
Epoch 1250 Each train cost time: 0.9203986883163452 Discriminator Loss: 1.3841  Generator Loss: 0.6867
Epoch 1300 Each train cost time: 0.8978909826278687 Discriminator Loss: 1.8547  Generator Loss: 2.2249
Epoch 1350 Each train cost time: 0.890495285987854 Discriminator Loss: 2.1113  Generator Loss: 2.3727
Epoch 1400 Each train cost time: 0.9004292297363281 Discriminator Loss: 1.6610  Generator Loss: 0.4504
Epoch 1450 Each train cost time: 0.8944595098495484 Discriminator Loss: 1.3307  Generator Loss: 0.6619
Epoch 1500 Each train cost time: 0.8915800333023072 Discriminator Loss: 1.5116  Generator Loss: 1.1923
Epoch 1550 Each train cost time: 0.9304086351394654 Discriminator Loss: 1.5851  Generator Loss: 1.6883
Epoch 1600 Each train cost time: 0.9014840984344482 Discriminator Loss: 1.4816  Generator Loss: 0.8158
Epoch 1650 Each train cost time: 0.8931485795974732 Discriminator Loss: 1.2682  Generator Loss: 1.0052
Epoch 1700 Each train cost time: 0.895546293258667 Discriminator Loss: 1.2445  Generator Loss: 1.3940
Epoch 1750 Each train cost time: 0.9041035795211791 Discriminator Loss: 1.3040  Generator Loss: 0.8444
Epoch 1800 Each train cost time: 0.9000577211380005 Discriminator Loss: 1.7634  Generator Loss: 0.3745
Epoch 1850 Each train cost time: 0.9327434206008911 Discriminator Loss: 2.0523  Generator Loss: 0.2408
Epoch 1900 Each train cost time: 0.9001765251159668 Discriminator Loss: 1.5126  Generator Loss: 1.4653
Epoch 1950 Each train cost time: 0.8934384155273437 Discriminator Loss: 1.7996  Generator Loss: 0.2896
Epoch 2000 Each train cost time: 0.9010148620605469 Discriminator Loss: 1.7054  Generator Loss: 0.3572
Epoch 2050 Each train cost time: 0.9008487892150879 Discriminator Loss: 2.7589  Generator Loss: 0.1203
Epoch 2100 Each train cost time: 0.8944020223617554 Discriminator Loss: 2.2154  Generator Loss: 0.1889
Epoch 2150 Each train cost time: 0.9390056228637695 Discriminator Loss: 1.6850  Generator Loss: 0.5668
Epoch 2200 Each train cost time: 0.8945643949508667 Discriminator Loss: 1.9379  Generator Loss: 0.2784
Epoch 2250 Each train cost time: 0.8946266174316406 Discriminator Loss: 1.2716  Generator Loss: 0.7856
Epoch 2300 Each train cost time: 0.8920586824417114 Discriminator Loss: 1.5820  Generator Loss: 0.3928
Epoch 2350 Each train cost time: 0.8919923448562622 Discriminator Loss: 1.7935  Generator Loss: 2.0607
Epoch 2400 Each train cost time: 0.9012992286682129 Discriminator Loss: 1.5061  Generator Loss: 0.4651
Epoch 2450 Each train cost time: 0.947036600112915 Discriminator Loss: 2.4640  Generator Loss: 0.1624
Epoch 2500 Each train cost time: 0.9093084621429444 Discriminator Loss: 1.7158  Generator Loss: 0.4453
Epoch 2550 Each train cost time: 0.9097314167022705 Discriminator Loss: 1.3763  Generator Loss: 0.5791
Epoch 2600 Each train cost time: 0.9021075344085694 Discriminator Loss: 1.8813  Generator Loss: 0.2736
Epoch 2650 Each train cost time: 0.9141985893249511 Discriminator Loss: 2.0998  Generator Loss: 0.2033
Epoch 2700 Each train cost time: 0.8959060335159301 Discriminator Loss: 1.6324  Generator Loss: 2.2755
Epoch 2750 Each train cost time: 0.9311578559875489 Discriminator Loss: 1.4867  Generator Loss: 0.4639
Epoch 2800 Each train cost time: 0.8890347909927369 Discriminator Loss: 1.8629  Generator Loss: 2.1433
Epoch 2850 Each train cost time: 0.9024470567703247 Discriminator Loss: 1.7613  Generator Loss: 1.7820
Epoch 2900 Each train cost time: 0.8930764675140381 Discriminator Loss: 1.3841  Generator Loss: 0.6472
Epoch 2950 Each train cost time: 0.8962572431564331 Discriminator Loss: 1.1587  Generator Loss: 1.1213
Epoch 3000 Each train cost time: 0.8990545558929444 Discriminator Loss: 1.3483  Generator Loss: 0.9560
Epoch 3050 Each train cost time: 0.9400939989089966 Discriminator Loss: 2.3048  Generator Loss: 0.1625
Epoch 3100 Each train cost time: 0.8948914766311645 Discriminator Loss: 1.5689  Generator Loss: 0.3997
Epoch 3150 Each train cost time: 0.8959512948989868 Discriminator Loss: 1.5571  Generator Loss: 0.4521
Epoch 3200 Each train cost time: 0.9032846593856811 Discriminator Loss: 1.7839  Generator Loss: 0.3067
Epoch 3250 Each train cost time: 0.8960964345932007 Discriminator Loss: 1.2776  Generator Loss: 0.8939
Epoch 3300 Each train cost time: 0.9024913072586059 Discriminator Loss: 2.3492  Generator Loss: 0.1662
Epoch 3350 Each train cost time: 0.9430712032318115 Discriminator Loss: 1.3356  Generator Loss: 0.7995
Epoch 3400 Each train cost time: 0.903332462310791 Discriminator Loss: 1.4728  Generator Loss: 0.4992
Epoch 3450 Each train cost time: 0.89660973072052 Discriminator Loss: 1.2482  Generator Loss: 1.2980
Epoch 3500 Each train cost time: 0.8960180473327637 Discriminator Loss: 1.3034  Generator Loss: 0.6658
Epoch 3550 Each train cost time: 0.8986538076400756 Discriminator Loss: 1.5665  Generator Loss: 1.3669
Epoch 3600 Each train cost time: 0.8986346101760865 Discriminator Loss: 1.6857  Generator Loss: 0.3176
Epoch 3650 Each train cost time: 0.9463444375991821 Discriminator Loss: 2.6364  Generator Loss: 0.1597
Epoch 3700 Each train cost time: 0.8995379114151001 Discriminator Loss: 2.1213  Generator Loss: 0.2259
Epoch 3750 Each train cost time: 0.9032630634307861 Discriminator Loss: 1.3718  Generator Loss: 1.7562

CelebA

Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.

In [ ]:
batch_size = 40
z_dim = 500
learning_rate = 2e-4
beta1 = 0.45

losses = []
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 1
save_path = "celeba_save"


celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
with tf.Graph().as_default():
    train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
          celeba_dataset.shape, celeba_dataset.image_mode, 
          save_folder=save_path)
""", base_i=8, load_path=save_path+"/7_gan.ckpt"""
begin train
Epoch 250 Each train cost time: 8.83396807193756 Discriminator Loss: 4.0418  Generator Loss: 0.0286
Epoch 500 Each train cost time: 8.874723720550538 Discriminator Loss: 3.2761  Generator Loss: 0.0694
Epoch 750 Each train cost time: 8.929072589874268 Discriminator Loss: 2.0051  Generator Loss: 0.2234
Epoch 1000 Each train cost time: 8.92107638835907 Discriminator Loss: 1.7842  Generator Loss: 0.3329
Epoch 1250 Each train cost time: 8.876678614616393 Discriminator Loss: 1.8349  Generator Loss: 0.2571
Epoch 1500 Each train cost time: 8.896831812858581 Discriminator Loss: 1.6766  Generator Loss: 0.3585
Epoch 1750 Each train cost time: 9.040506191253662 Discriminator Loss: 1.6228  Generator Loss: 0.4657
Epoch 2000 Each train cost time: 8.972160334587096 Discriminator Loss: 2.0726  Generator Loss: 0.2081
Epoch 2250 Each train cost time: 8.950370697975158 Discriminator Loss: 1.6862  Generator Loss: 0.3879
Epoch 2500 Each train cost time: 8.970361499786376 Discriminator Loss: 1.7869  Generator Loss: 0.3039

Submitting This Project

When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.